/* eslint-disable no-undef */
import Vue from 'vue';
import Router from 'uni-simple-router';
import modules from './modules';
import { uploadmaidian } from '@/utils/maidian.js';
import { getToken } from '@/utils/local';
import { setLocal, removeLocalStorage } from '@/utils/utils';

import { config } from '@/config';

// import _ from 'lodash';
Vue.use(Router);

const whiteList = ['/login', '/404'];
let lastPath = null;

const router = new Router(
  {
    mode: 'history',
    h5: {
      vueRouterDev: true // 完全使用vue-router开发 默认 false
    },
    routes: modules // 路由表
  });

const checkedQuery = function(query) {
  const token = query.token;
  if (token) {
    setLocal({ token });
  }
};

router.beforeEach((to, from, next) => {
  checkedQuery(from.query);

  const hasToken = getToken();
  const {
    meta,
    name
  } = to;

  if (!['listDetailSp', 'listDetail'].includes(name)) {
    removeLocalStorage('listDetailRenderData');
    removeLocalStorage('templateBusinessFields');
  }

  if (meta && meta.title) {
    document.title = meta.title || config.title;
  } else {
    document.title = config.title;
  }

  if (hasToken) {
    if (lastPath) {
      next(lastPath);
      lastPath = null;
    } else if (to.path === '/login') {
      next('/');
    } else {
      next();
    }
    setTimeout(() => {
      // 浩哥的埋点
      uploadmaidian();
    }, 1000);
  } else if (whiteList.some(m => to.path.startsWith(m))) {
    next();
  } else { // 不在白名单且未登录
    lastPath = from.fullPath;
    next({
      path: '/login'
    });
  }
});

// router.afterEach((to, from) => {});
export default router;
